package com.example.demo.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;

/**
 * @Author：zhoutaoming
 * @name：Url
 * @Date：2024/8/7 16:32
 * @Version 1.0
 */
public class UrlDownload {
    public static void download(String urlString, String filename) throws Exception {

        URL url = new URL(urlString); // 构造URL
        URLConnection con = url.openConnection();  // 打开链接
//        con.setConnectTimeout(1*1000);  //设置请求超时为5s
        Thread.sleep(65*1000);
        InputStream is = con.getInputStream();  // 输入流

        byte[] bs = new byte[1024];  // 1K的数据缓冲
        int len;  // 读取到的数据长度
        int i = filename.length();
        for(i--;i>=0 && filename.charAt(i) != '\\' && filename.charAt(i) != '/';i--);
        String s_dir = filename.substring(0, i);
        File dir = new File(s_dir);  // 输出的文件流
        if(!dir.exists()){
            dir.mkdirs();
        }
        OutputStream os = new FileOutputStream(filename);
        // 开始读取
        while ((len = is.read(bs)) != -1) {
            os.write(bs, 0, len);
        }
        // 完毕，关闭所有链接
        os.close();
        is.close();
    }
    public static void main(String[] args) {
        try {
            download("https://picture.wenwo.com/fimg/a1bf14f7f8a8b17e0f2ae7d25354f49a.jpg","D:\\1.jpg");
        }catch (Exception e){
            e.printStackTrace();
        }

    }
}
